import { ReactView, reactControl, ReactViewControl, ReactViewState } from "pao-aop-client";

import React from "react";

import { addon, log, getObject, Ref } from "pao-aop";
import { ProductSign, ProductSignCondition, IProductSignService } from "src/models/productSign";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import { message } from "antd";
import { ROUTE_PATH, change_structure, onRowSkipClick, isPermission } from "../../app/util-tool";
import { PermissionList } from "../../app/permission";
import { IProductTypeService } from "src/models/productType";

/**
 * 组件：产品标识列表视图状态
 */
export interface ProductSignViewState extends ReactViewState {
    /** 产品标识列表数据源 */
    data_source?: ProductSign[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: ProductSignCondition;
    /** 产品类型列表 */
    product_data?: any;
    /** 是否显示提示框 */
    visible?: boolean;
    /** 提示框提示语 */
    modal_contexts?: string;
    /** 删除的品类Id */
    category_id?: string;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：产品标识列表视图
 * 控制产品标识列表视图
 */
export class ProductSignView extends ReactView<ProductSignViewControl, ProductSignViewState> {
    private columns_data_source = [{
        title: '产品标识名称',
        dataIndex: 'handle_name',
        key: "handle_name",
        width: 500
    },
    {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    },
    {
        title: '产品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
        render: (text: string, record: any, index: any) => {
            return <a onClick={() => onRowSkipClick(this.props, record, index, ROUTE_PATH.categoryTemplateDetail)}>{text}</a>;
        }
    },
    {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
        // render: ((create_date: Date) =>
        //     create_date.toString()
        // )
    }];

    constructor(props: any) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 10,
            loading: false
        };
    }

    /** 
     * 分页回调事件 
     */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }

    /** 
     * 改变分页数量回调事件 
     */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }

    /**
     * 获取品类服务
     */
    productServices?() {
        return getObject(this.props.productSignService_Fac!);
    }

    /**
     * 初始化产品类型服务 
     */
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }

    /**
     * 查询回调
     */
    private searchCategory = (e: any, val: any) => {
        this.setState({
            condition: val,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }

    /**
     * 查询列表信息
     */
    async queryList(condition: ProductSignCondition, page: number, count: number) {
        const data = await this.productServices!()!.get_product_list!(condition, page, count)!;
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;

        let product_map = change_structure('product_type_name', product_data!.result);
        this.setState({
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data!.result : [],
            product_data: product_map
        });
    }

    /**
     * table其他按钮回调
     */
    private handleOtherClick = (type: any, contents: any) => {
        /** 自定义图标按钮回调事件 */
        if ('icon_edit' === type) {
            console.log('自定义按钮edit返回值：', contents);
            this.editCategory(contents);
        }
    }

    /**
     * 创建新品目回调
     */
    private createProductSign = () => {
        console.log("创建新品目回调");
        this.props.history!.push(ROUTE_PATH.changeProductSign);
    }

    /**
     * 编辑行的类目回调
     */
    private editCategory = (record: any) => {
        console.log("编辑行的类目回调");
        console.log(record);
        this.props.history!.push(ROUTE_PATH.changeCategoryTemplate + `/${record.id}`);
    }

    // /** 确定回调事件 */
    // handleOk = () => {
    //     this.setState({
    //         visible: false,
    //     });
    //     /** 删除 */
    //     this.delete(this.state.category_id!);
    // }
    // /** 取消事件 */
    // handleCancel = () => {
    //     this.setState({
    //         visible: false,
    //     });
    // }

    // /**
    //  * 是否被引用
    //  * @param id 
    //  */
    // async isAllowDelete(id: string) {
    //     let result = await this.productServices!()!.is_allow_delete!([id])!;
    //     if (result) {
    //         this.delete(id);

    //     } else {
    //         this.setState({
    //             category_id: id,
    //             visible: true,
    //             modal_contexts: '改品类已被单品引用，确认需要删除？'
    //         });
    //     }
    // }
    /**
     * 删除品类方法
     */
    private delete = (id: string) => {
        this.setState({
            loading: true
        });
        this.productServices!()!.delete!([id])!
            .then(info => {
                if (info) {
                    message.info("删除成功");
                    this.queryList({}, 1, 10)
                        .then(() => {
                            this.setState({
                                loading: false
                            });
                        })
                        .catch(error => {
                            log("changeProductViewControl", error.message);
                        });
                } else {
                    this.setState({
                        loading: false
                    });
                    message.error("删除失败");
                }
            }
            )
            .catch(error => {
                console.log(error);
            });
    }
    /**
     * 删除品目回调
     */
    private deleteCategory = (record: any) => {
        console.log("删除品目回调");
        /** 删除 */
        this.delete(this.state.category_id!);
    }

    /**
     * 重置回调
     */
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {},
            loading: true
        });
        this.queryList({}, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }

    componentDidMount() {
        this.setState({
            loading: true
        });
        let condition: ProductSignCondition = {};
        this.queryList(condition, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }

    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.ProductSign_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let { data_source } = this.state;

        let sign_frame_props = {
            loading: this.state.loading,
            edit_form_items_props: [{
                type: InputType.input,
                label: "产品标识名称",
                decorator_id: "handle_name",
                option: {
                    placeholder: "请输入产品标识名称"
                }
            },
            {
                type: InputType.input,
                label: "产品标识",
                decorator_id: "handle_code",
                option: {
                    placeholder: "请输入产品标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date",
            }],
            btn_props: [{
                label: '新建产品标识',
                btn_method: this.createProductSign,
                icon: 'plus'
            }],
            showTable: (
                <NTOperationTable
                    data_source={data_source}
                    columns_data_source={this.columns_data_source}
                    on_click_del={this.deleteCategory}
                    bordered={false}
                    // onClick={this.onRowClick}
                    on_icon_click={this.handleOtherClick}
                    other_label_type={[{ type: 'icon', label_key: 'icon_edit', label_parameter: { icon: 'antd@edit' } }]}
                    table_size='middle'
                    showHeader={true}
                    total={this.state.total_data}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                    rowKey='id'
                />
            ),
            search_cb: this.searchCategory,
            reset_cb: this.reset
        };

        return (
            <SignFrameLayout {...sign_frame_props} />
        );
    }
}

/**
 * 控件：产品标识列表视图
 * 控制产品标识列表视图
 */
@addon('ProductView', '产品标识列表视图', '控制产品标识列表视图')
@reactControl(ProductSignView, true)
export class ProductSignViewControl extends ReactViewControl {
    /**
     * 产品标识服务
     */
    public productSignService_Fac?: Ref<IProductSignService>;

    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;
}